import React, { useState, useEffect, useRef, useMemo } from 'react';
import { View, TouchableOpacity } from 'react-native';
import { useTranslation } from 'react-i18next';
import { userApi, RegisterParams } from '@/services/api/userApi';
import { useDispatch, useSelector } from 'react-redux';
import { type CountryItem } from '../common/CountryPicker';
import {
  fetchCountries,
  selectSelectedCountry,
  setSelectedCountry,
} from '@/store/slices/countrySlice';
import store, { AppDispatch } from '@/store';
import { useForm, Controller } from 'react-hook-form';
import GeoLocation from '@/utils/location';
import Toast from '@/utils/toast';
import Owner from '@/assets/icon/owner.svg';
import Installer from '@/assets/icon/installer.svg';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useCountDown, useDebounceFn } from 'ahooks';
import { ErrorText } from '@/components/ErrorText';
import Register from '@/assets/icon/register.svg';
import {
  Button,
  CodeTextInput,
  TextInput as BaseTextInput,
  useAppTheme,
  Icon,
  Text,
} from 'tsun-smart-ui';
import { KeyboardAwareScrollView } from 'react-native-keyboard-controller';
import usePicker from '@/hooks/usePicker';
import StringUtils from '@/utils/StringUtils';
import { ApiResponse } from '@/services/http';
// 定义表单数据类型
type RegisterFormData = {
  nickname: string;
  email: string;
  verificationCode: string;
  password: string;
  confirmPassword: string;
  companyName: string;
  parentCode: string;
  installer?: string;
};
const SITES: string[] = ['user.europe_site'];
const RegisterScreen = ({
  route: { params },
  navigation,
}: ReactNavigation.RootStackScreenProps<'Register'>) => {
  const dispatch = useDispatch<AppDispatch>();
  const { i18n, t } = useTranslation();
  const {
    control,
    handleSubmit,
    formState: { errors },
    trigger,
    getValues,
    watch,
    setValue,
  } = useForm<RegisterFormData>({
    defaultValues: {
      nickname: '',
      email: '',
      verificationCode: '',
      password: '',
      confirmPassword: '',
      companyName: '',
      parentCode: '',
      installer: '',
    },
    mode: 'onChange',
  });
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const selectedCountry = useSelector(selectSelectedCountry);
  const isChineseUser = selectedCountry?.code === 'ct.china';
  const [timezoneList, setTimezoneList] = useState<CountryItem['zoneList']>([]);
  const password = watch('password');
  const btnRef = useRef<{
    setTargetDate: (date: number) => void;
  }>(null);
  const theme = useAppTheme();
  const { bottom } = useSafeAreaInsets();
  const [PickerDataList, setPickerDataList] = useState<string[]>([]);
  const [selectedSite, setSelectedSite] = useState<string>('user.europe_site'); // 默认中国站
  const [userType, setUserType] = useState<1 | 2>(params?.userType ?? 1); // 默认业主角色
  const [Picker, selectedValue, setSelectedValue] = usePicker(PickerDataList);
  const roles = [
    {
      label: 'message.userswhoOwnOrAlreadyOwnapowerStation',
      userType: 'personal.Owner',
      value: 1,
      icon: Owner,
    },
    {
      label: 'message.userswhoProvideServicesforPropertyOwners',
      userType: 'settings.installer.operator',
      value: 2,
      icon: Installer,
    },
  ] as const;

  // 第三步：自动跳转登录倒计时
  useEffect(() => {
    if (store.getState().country.countries.length === 0) {
      Toast.showLoading();
      dispatch(fetchCountries())
        .unwrap()
        .then(async (value) => {
          await GeoLocation.requestPermissions();
          const locationInstance = new GeoLocation();
          const { country } = await locationInstance.getCurrentPosition();
          //默认德国  后期这里替换地图厂商获取实际国家
          const result = value.find((item) => {
            return item.value === country;
          })!;
          dispatch(setSelectedCountry(result));
          setSelectedValue([t(result.zoneList[0].code)]);
        })
        .finally(() => {
          Toast.hideLoading();
        });
    }
  }, [dispatch, t]);
  useEffect(() => {
    if (selectedCountry) {
      setTimezoneList(
        selectedCountry.zoneList.map((item) => {
          return {
            ...item,
            code: t(item.code),
          };
        })
      );
      setSelectedValue([t(selectedCountry.zoneList[0].code)]);
    }
  }, [selectedCountry, t]);
  const handleNext = () => {
    if (!selectedSite) {
      Toast.warning({
        message: t('userSetting.select.station', {
          defaultValue: '请选择站点',
        }),
      });
    }
    navigation.push('Register', {
      initialPage: 1,
      userType,
    });
  };

  // 发送验证码
  const handleSendVerificationCode = async () => {
    const isValid = await trigger('email');
    if (!isValid) {
      return;
    }
    const { email } = getValues();
    // 使用 userApi 发送验证码
    btnRef.current?.setTargetDate(Date.now() + 3 * 60 * 1000);
    try {
      let response: ApiResponse<any>;
      if (isChineseUser) {
        response = await userApi.sendOneTimePhoneCode(email, i18n.language);
      } else {
        response = await userApi.sendRegisterCode(email);
      }

      if (response && response.code === 0) {
        // 发送成功，开始倒计时
        Toast.success({
          message: t('common.mail.code.send', { defaultValue: '验证码已发送' }),
        });
      }
    } catch {
      btnRef.current?.setTargetDate(void 0);
    }
  };
  const { run: debounceRegister } = useDebounceFn(
    (values: RegisterFormData) => handleRegister(values),
    { wait: 300 }
  );

  // 提交注册
  const handleRegister = async (values: RegisterFormData) => {
    try {
      const {
        companyName,
        parentCode,
        email,
        password,
        verificationCode: code,
        nickname,
      } = values;
      setLoading(true);
      // 准备注册参数 - 包含国家和时区以及站点
      const registerParams: RegisterParams = {
        email: email.trim(),
        phone: email.trim(),
        code,
        password: password.trim(),
        userType,
        lng: i18n.language,
        center: selectedSite, // Use the selected site as the data center
        county: selectedCountry?.value,
        timeZone: timezoneList.find((item) => t(item.code) === selectedValue[0])
          ?.value,
        nickname,
        companyCode: userType === 1 ? parentCode : undefined,
      };

      // 如果是安装商/运营商，添加额外的参数
      if (userType === 2) {
        registerParams.companyName = companyName;
        if (parentCode) {
          registerParams.parentCode = parentCode;
        }
      }

      // 使用 userApi 注册
      if (isChineseUser) {
        await userApi.registerByPhoneNumber(registerParams);
      } else {
        await userApi.register(registerParams);
      }
      navigation.push('Register', {
        initialPage: 2,
        timeout: Date.now() + 1000 * 3,
      });
    } finally {
      setLoading(false);
    }
  };
  return (
    <View className="flex-1">
      {params?.initialPage === 2 && (
        <RegisterResultScreen
          navigation={navigation}
          timeout={params.timeout!}
        />
      )}
      {params?.initialPage === 1 && (
        <View key={'stepTwo'} className="flex-1">
          <View className="flex-1">
            <KeyboardAwareScrollView
              className="flex-1"
              contentContainerStyle={{ padding: 20, rowGap: 10 }}
            >
              {/* 国家/地区选择 */}
              <View>
                <BaseTextInput
                  editable={false}
                  value={t(selectedCountry?.code!)}
                  onPress={() => {
                    navigation.navigate('CountryPicker', {});
                  }}
                  label={t('userSetting.basicInfo.form.label.countryRegion', {
                    defaultValue: '国家/地区',
                  })}
                  right={
                    <Icon
                      name="right"
                      size={10}
                      color={theme.colors?.neutral?.primary}
                    />
                  }
                  left="area"
                />
              </View>

              {/* 时区选择 */}
              <View>
                <BaseTextInput
                  editable={false}
                  label={t('sys.app.time.zone', { defaultValue: '时区' })}
                  value={selectedValue[0]}
                  right={
                    <Icon
                      name="right"
                      size={10}
                      color={theme.colors?.neutral?.primary}
                    />
                  }
                  left="timezone"
                  onPress={() => {
                    setPickerDataList(timezoneList.map((item) => t(item.code)));
                    requestAnimationFrame(() => {
                      Picker.show();
                    });
                  }}
                />
              </View>
              {/* 昵称字段 */}
              <Controller
                name="nickname"
                control={control}
                rules={{
                  required: t('userSetting.form.error.nickname.required', {
                    defaultValue: '请输入昵称',
                  }),
                }}
                render={({ field: { onChange, value } }) => {
                  return (
                    <View>
                      <BaseTextInput
                        label={t('sysuser.nickname', { defaultValue: '昵称' })}
                        left="nickname"
                        placeholder={t(
                          'userSetting.form.error.nickname.required',
                          {
                            defaultValue: '请输入昵称',
                          }
                        )}
                        value={value}
                        onChangeText={onChange}
                        autoCapitalize="none"
                        textContentType="nickname"
                      />
                      <View className="pt-2 ml-14">
                        {errors.nickname && (
                          <ErrorText text={errors.nickname.message!} />
                        )}
                      </View>
                    </View>
                  );
                }}
              />
              {/* 邮箱输入 */}
              <View>
                <Controller
                  name="email"
                  control={control}
                  rules={{
                    required: t(
                      isChineseUser ? 'sysuser.phone' : 'table.inputemailTip'
                    ),
                    validate: (value) => {
                      if (
                        isChineseUser &&
                        StringUtils.isValidPhoneNumber(value)
                      ) {
                        return true;
                      }
                      if (!isChineseUser && StringUtils.isValidEmail(value)) {
                        return true;
                      }
                      return isChineseUser
                        ? t('sysuser.phone.validate')
                        : t('password.enterRightEmail');
                    },
                  }}
                  render={({ field: { onChange, value } }) => (
                    <BaseTextInput
                      left={isChineseUser ? 'mobile' : 'email'}
                      label={t(isChineseUser ? 'sysuser.phone' : 'table.email')}
                      placeholder={t(
                        isChineseUser
                          ? 'password.phonePlaceholder4'
                          : 'table.inputemailTip'
                      )}
                      value={value}
                      onChangeText={onChange}
                      keyboardType={
                        isChineseUser ? 'phone-pad' : 'email-address'
                      }
                      textContentType={
                        isChineseUser ? 'telephoneNumber' : 'emailAddress'
                      }
                      autoCapitalize="none"
                    />
                  )}
                />
                <View className="pt-2 ml-14">
                  {errors.email && <ErrorText text={errors.email.message!} />}
                </View>
              </View>

              {/* 验证码输入 */}
              <View>
                <Controller
                  name="verificationCode"
                  control={control}
                  rules={{
                    required: t('password.accountPlaceholder3', {
                      defaultValue: '请输入验证码',
                    }),
                  }}
                  render={({ field: { onChange, value } }) => (
                    <CodeTextInput
                      btnRef={btnRef}
                      maxLength={6}
                      left="Safety"
                      placeholder={t('password.accountPlaceholder3', {
                        defaultValue: '请输入验证码',
                      })}
                      i18n={{
                        sendText: t('common.code.send', {
                          defaultValue: '发送验证码',
                        }),
                        resendTemplate: '{seconds}',
                      }}
                      buttonStyle={{
                        borderRadius: 6,
                      }}
                      value={value}
                      onChangeText={onChange}
                      keyboardType="number-pad"
                      autoCapitalize="none"
                      onPress={handleSendVerificationCode}
                    />
                  )}
                />
                <View className="pt-2 ml-14">
                  {errors.verificationCode && (
                    <ErrorText text={errors.verificationCode.message!} />
                  )}
                </View>
              </View>

              {/* 密码输入 */}
              <View>
                <Controller
                  name="password"
                  control={control}
                  rules={{
                    required: t('login.form.password.placeholder', {
                      defaultValue: '请输入密码',
                    }),
                    pattern: {
                      value: /(?=.*[a-z])/,
                      message: t('personal.passwordScore'),
                    },
                    minLength: {
                      value: 6,
                      message: t('personal.passwordScore'),
                    },
                  }}
                  render={({ field: { onChange, value } }) => (
                    <BaseTextInput
                      label={t('datasourceconf.password', {
                        defaultValue: '密码',
                      })}
                      value={value}
                      onChangeText={onChange}
                      secureTextEntry={!showPassword}
                      left="password"
                      onBlur={() => {
                        trigger('confirmPassword');
                      }}
                      right={
                        <Icon
                          name={showPassword ? 'eye' : 'eye-off'}
                          onPress={() => setShowPassword(!showPassword)}
                          size={16}
                        />
                      }
                      placeholder={t('login.form.password.placeholder', {
                        defaultValue: '请输入密码',
                      })}
                    ></BaseTextInput>
                  )}
                />
                <View className="pt-2 ml-14">
                  {errors.password && (
                    <ErrorText text={errors.password.message!} />
                  )}
                </View>
              </View>

              {/* 确认密码输入 */}
              <View>
                <Controller
                  name="confirmPassword"
                  control={control}
                  rules={{
                    required: t('common.password.newpassword.tip3', {
                      defaultValue: '请再次输入密码',
                    }),
                    validate: (value) =>
                      value === password ||
                      t('personal.passwordRule', {
                        defaultValue: '两次输入的密码不一致',
                      }),
                  }}
                  render={({ field: { onChange, value } }) => (
                    <BaseTextInput
                      value={value}
                      onChangeText={onChange}
                      secureTextEntry={!showConfirmPassword}
                      left="repassword"
                      right={
                        <Icon
                          name={showConfirmPassword ? 'eye' : 'eye-off'}
                          onPress={() =>
                            setShowConfirmPassword(!showConfirmPassword)
                          }
                          size={16}
                        />
                      }
                      placeholder={t('common.password.newpassword.tip3', {
                        defaultValue: '请输入密码',
                      })}
                    />
                  )}
                />
                <View className="pt-2 ml-14">
                  {errors.confirmPassword && (
                    <ErrorText text={errors.confirmPassword.message!} />
                  )}
                </View>
              </View>

              {/* 安装商特有字段 */}
              {userType === 2 && (
                <View>
                  <Controller
                    name="companyName"
                    control={control}
                    rules={{
                      required: t('common.company.name', {
                        defaultValue: '请输入公司名称',
                      }),
                    }}
                    render={({ field: { onChange, value } }) => (
                      <BaseTextInput
                        label={t('sysdept.installer.companyname', {
                          defaultValue: '公司名称',
                        })}
                        left="company"
                        placeholder={t('common.company.name', {
                          defaultValue: '请输入公司名称',
                        })}
                        value={value}
                        onChangeText={onChange}
                      />
                    )}
                  />
                  <View className="pt-2 ml-14">
                    {errors.companyName && (
                      <ErrorText text={errors.companyName.message!} />
                    )}
                  </View>
                </View>
              )}

              <View>
                <Controller
                  name="installer"
                  control={control}
                  render={({ field: { onChange, value } }) => (
                    <BaseTextInput
                      onPress={() => {
                        navigation.navigate('InstallerPicker', {
                          setValue,
                        });
                      }}
                      left="installer"
                      label={t('template.parent_installer_dealer_code', {
                        defaultValue: '上级安装商、轻销商代码',
                      })}
                      placeholder={t('sysrole.please_select')}
                      editable={false}
                      right={
                        <Icon
                          name="right"
                          size={10}
                          color={theme.colors?.neutral?.primary}
                        />
                      }
                      value={value}
                      onChangeText={onChange}
                    />
                  )}
                />
              </View>
            </KeyboardAwareScrollView>
            <View
              className="px-6 pt-3 bg-background-0"
              style={{
                paddingBottom: bottom + 27,
              }}
            >
              <Button
                loading={loading}
                disabled={loading}
                title={t('sys.operation.register')}
                onPress={handleSubmit(debounceRegister)}
              ></Button>
            </View>
          </View>
        </View>
      )}
      {!params?.initialPage && (
        <View
          key={'stepOne'}
          className="flex-1 px-4 mt-4 justify-between"
          style={{
            paddingBottom: bottom + 27,
          }}
        >
          {/* 步骤1：选择角色 */}
          <View className="flex-1">
            {/* 站点选择 */}
            <View className="mb-3">
              <BaseTextInput
                inputWrapperStyle={{
                  borderRadius: 8,
                }}
                onPress={() => {
                  setPickerDataList(SITES.map((item) => t(item)));
                  requestAnimationFrame(() => {
                    Picker.show();
                  });
                }}
                editable={false}
                value={t(selectedSite)}
                left="earth"
                right={
                  <Icon
                    name="right"
                    size={10}
                    color={theme.colors?.neutral?.primary}
                  />
                }
                label={t('user.current_site', { defaultValue: '当前站点' })}
              />
            </View>
            <Text className="mt-3  mb-2" variant="bodyMedium">
              {t('sysrole.select', {
                defaultValue: '请选择你的角色',
              })}
            </Text>

            <View className="mb-5">
              {roles.map((item) => {
                return (
                  <TouchableOpacity
                    key={item.value}
                    className="px-5 flex-row flex-between h-20 border rounded-lg mb-5"
                    style={[
                      {
                        backgroundColor:
                          userType === item.value
                            ? theme.colors?.brand?.primaryLight
                            : theme.colors?.neutral?.white,
                        borderColor:
                          userType === item.value
                            ? theme.colors?.brand?.primary
                            : theme.colors?.background?.primary,
                      },
                    ]}
                    onPress={() => setUserType(item.value)}
                  >
                    <View className="w-[220px] flex-row gap-x-3 items-center">
                      {React.createElement(item.icon, {
                        width: 36,
                        height: 36,
                        color:theme.colors?.brand?.primary
                      })}
                      <View>
                        <Text className="mb-1" variant="bodyStrong">
                          {t(item.userType)}
                        </Text>
                        <Text
                          numberOfLines={2}
                          style={{
                            color: theme.colors?.neutral?.primary,
                          }}
                          variant="caption"
                        >
                          {t(item.label)}
                        </Text>
                      </View>
                    </View>
                    {userType === item.value && (
                      <Icon
                        name="check-circle"
                        color={theme.colors?.brand?.primary}
                        size={18}
                      ></Icon>
                    )}
                  </TouchableOpacity>
                );
              })}
            </View>
          </View>
          <Button title={t('settings.nextStep')} onPress={handleNext}></Button>
        </View>
      )}
    </View>
  );
};
const RegisterResultScreen = ({
  timeout,
  navigation,
}: {
  timeout: number;
  navigation: ReactNavigation.RootStackScreenProps<'Register'>['navigation'];
}) => {
  const { t } = useTranslation();
  const [registerCount] = useCountDown({
    targetDate: timeout,
    onEnd() {
      navigation.popToTop();
    },
  });
  return (
    <View key={'result'} className="flex-1 items-center mt-32">
      <Register width={48} height={48} />
      <Text variant="titleLarge" className=" text-center mb-[6px] mt-[22px]">
        {t('note.registration_success')}
      </Text>
      <Text className=" text-center">
        {`${Math.round(registerCount / 1000)}${t('common.navi')}`}
      </Text>
    </View>
  );
};
export default RegisterScreen;
